package com.bsoft.exchange.service;

import java.sql.SQLException;
import java.util.Date;

import com.alibaba.fastjson.JSONObject;
import com.bsoft.exchange.dao.his.YBServiceMapper;
import com.bsoft.exchange.pojo.OutResponse;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.bsoft.exchange.dao.his.AppointmentPayCancelMapper;
import com.bsoft.exchange.dao.his.SystemConfigMapper;
import com.bsoft.exchange.domain.YyxxForCancel;
import com.bsoft.exchange.pojo.AppointmentPayCancelPojo;
import com.bsoft.exchange.pojo.ReturnVisitPaymentCancelPojo;
import com.bsoft.exchange.util.BaseResponse;
import com.bsoft.exchange.util.Constant;
import com.bsoft.exchange.util.DateUtil;

@Service
public class AppointmentPayCancelService {

    private static final Logger log = LoggerFactory.getLogger(AppointmentPayCancelService.class);

    @Autowired
    AppointmentPayCancelMapper appointmentPayCancelMapper;


    @Autowired
    SystemConfigMapper systemConfigMapper;

    @Autowired
    YBService ybService;

    @Autowired
    YBServiceMapper ybServiceMapper;

//	@Autowired
//	DateUtil dateUtil;

    @Transactional(value = "hisTransactionManager", rollbackFor = Exception.class)
    public BaseResponse<String> appointmentPayCancel(AppointmentPayCancelPojo appointmentPayCancelPojo) throws SQLException {
        BaseResponse baseResponse = new BaseResponse<>();
        int jgid = 1;
        int yyxh = appointmentPayCancelPojo.getOrderId();
        String refundReason = appointmentPayCancelPojo.getRefundReason();
        int mzlb = appointmentPayCancelPojo.getOutpatientType();
        //if(scheduleDate!=null&&!"".equals(scheduleDate))
        if (refundReason == null || "".equals(refundReason)) {
            refundReason = "个人原因";
        }


        //获取YYZT,GHKS,YSDM,BRXM,YYSJ,HYXH,ZBLB,GHXH
        YyxxForCancel yyxxForCancel = appointmentPayCancelMapper.getYyxx(yyxh, jgid);
        int yyzt = yyxxForCancel.getYyzt();
        String ghks = yyxxForCancel.getGhks();
        String brxm = yyxxForCancel.getBrxm();
        Date yysj = yyxxForCancel.getYysj();
        int hyxh = yyxxForCancel.getHyxh();
        int zblb = yyxxForCancel.getZblb();
        int ghxh = yyxxForCancel.getGhxh();
        String ysdm = yyxxForCancel.getYsdm();

        //取消预约
        baseResponse = yyqxFunc(jgid, yyxh, refundReason, yyzt, yysj, brxm, hyxh, yyxxForCancel.getTgbz(),ghxh);
        if (baseResponse.getCode() == -1) {
            return baseResponse;
        }

        //判断是否支付，若已支付做退号处理
        int zfzt = 0;
        //已挂号表示已支付
        if (ghxh > 0) {
            zfzt = 1;
        }
        if (zfzt == 1) {
            baseResponse = thclFunc(jgid, yyxh, zblb, ghxh, brxm, mzlb, ghks, ysdm, yysj);
            if (baseResponse.getCode() == -1) {
                return baseResponse;
            }
        }

        String infofeeInfomation = "预约取消成功,预约流水号：" + yyxh;
        JSONObject data = new JSONObject(true);
        data.put("feeInfomation", infofeeInfomation);
        baseResponse.setCode(Constant.successTag);
        baseResponse.setData(data);
        baseResponse.setMessage("预约取消成功");
        return baseResponse;


    }

    /**
     * 复诊配药申请取消
     *
     * @param returnVisitPaymentCancelPojo
     * @return
     * @throws SQLException
     */
    @Transactional(value = "hisTransactionManager", rollbackFor = Exception.class)
    public BaseResponse<String> returnVisitPaymentCancel(ReturnVisitPaymentCancelPojo returnVisitPaymentCancelPojo) throws SQLException {
        BaseResponse<String> baseResponse = new BaseResponse<>();
        int jgid = 1;
        int ghxh = returnVisitPaymentCancelPojo.getRegisteredSerialNo();

        Date now = new Date();


        Integer mzlb = appointmentPayCancelMapper.getMzlb(ghxh, jgid);
        if (mzlb == null || mzlb == 0) {
            baseResponse.setCode(Constant.errorTag);
            baseResponse.setMessage("获取mzlb失败，挂号序号：" + ghxh);
            return baseResponse;
        }

        Integer jzzt = appointmentPayCancelMapper.getJzzt(ghxh, jgid);
        if (jzzt != 0) {
            baseResponse.setCode(Constant.errorTag);
            baseResponse.setMessage("该记录已就诊，不能取消，挂号序号：" + ghxh);
            return baseResponse;
        }

        Long jgidLong = Long.valueOf(jgid);
        String czgh = "900002";
        //更新退号标志：
        appointmentPayCancelMapper.updateYyqxGhmx(ghxh, jgid);

        //插入MS_THMX
        appointmentPayCancelMapper.updateYyqxThmx(ghxh, czgh, mzlb, now, jgid);

        baseResponse.setCode(Constant.successTag);
        baseResponse.setMessage("复诊配药申请取消成功");
        return baseResponse;
    }

    /**
     * 预约取消功能
     *
     * @throws SQLException
     */
    private BaseResponse<String> yyqxFunc(int jgid, int yyxh, String qxyy, int yyzt, Date yysj, String brxm, int hyxh, int tgbz,int ghxh) throws SQLException {
        BaseResponse<String> baseResponse = new BaseResponse<>();


        if (yyzt == 2) {
            baseResponse.setCode(Constant.errorTag);
            baseResponse.setMessage("该预约记录已取消");
            return baseResponse;
        } else if (yyzt == 3) {
            baseResponse.setCode(Constant.errorTag);
            baseResponse.setMessage("该预约记录已标记爽约，不能取消");
            return baseResponse;
        }
        Long jgidLong = Long.valueOf(jgid);
        Date now = new Date();
        if (tgbz == 0) {
            //必须提前n天预约,少于这个天数，提示取消作为爽约处理
            //Select mrz from gy_xtcs where csmc = ‘GHYY_YYTQTS’

            int qxkz = 0;//=1表示不能取消

            Integer num = appointmentPayCancelMapper.getJzlsNum((long) ghxh);
            if(num > 0){
                baseResponse.setCode(Constant.errorTag);
                baseResponse.setMessage("该号已就诊，不能取消！");
                return baseResponse;
            }

            //	String tsString = systemConfigMapper.getValueByConfigName(jgidLong, "GHYY_QXYYTQTS");
        //	int ts = 1;
//            int ts = Integer.valueOf(systemConfigMapper.getValueByConfigName(jgidLong, "GHYY_QXYYTQTS"));
//
//        //	Date jzsj = null;
//            Date jzsj = DateUtil.addDateToDay(yysj, -ts);
//
//            if (now.getTime() > jzsj.getTime())//比较时间大小
//            {
//                qxkz = 1;
//            } else {
//                qxkz = 0;
//            }
//
//            if (qxkz == 1) {
//                baseResponse.setCode(Constant.errorTag);
//                baseResponse.setMessage("预约的号已过了取消时间，无法完成取消操作");
//                return baseResponse;
//            }
        }


//        String czgh = systemConfigMapper.getValueByConfigName(jgidLong, "ZSYY_MRGH");
        String czgh = "900001";


//	更新预约信息.取消时间=当前时间，取消人=当前操作员，预约状态=取消
//			update GHYY_YYXX set QXSJ = :ldt_qxsj,QXR = :go_user.userid,QXYY = :as_qxyy,YYZT = 2,SYBZ = :ll_sybz where YYXH = :al_yyxh and JGID =
        appointmentPayCancelMapper.updateYyqxYyxx(now, czgh, qxyy, yyxh, jgid);
//	try {
////	appointmentPayCancelMapper.updateYyqxYyxx(now, brxm, qxyy, yyxh, jgid);
//	appointmentPayCancelMapper.updateYyqxYyxx(now, brxm, qxyy, 91, 1);
//	} catch (Exception e) {
//		e.printStackTrace();
//		baseResponse.setCode(Constant.errorTag);
//		baseResponse.setMessage("处理失败");
//		return baseResponse;
//	}

        //在号源信息表中清空所有号源序号的预约序号，病人ID，病人姓名
//			update GHYY_HYXX set YYXH = 0,BRID = null,BRXM = null where JLXH = :ll_hyxh and JGID = :go_jgxx.il_jgid
        appointmentPayCancelMapper.updateYyqxHyxx(hyxh, jgid);

        baseResponse.setCode(Constant.successTag);
        return baseResponse;
    }

    /**
     * 退号处理
     */
    private BaseResponse<String> thclFunc(int jgid, int hyxh, int zblb, int ghxh, String brxm, int mzlb, String ksdm, String ysdm, Date yysj) {
        BaseResponse<String> baseResponse = new BaseResponse<>();
        Date now = new Date();

        Integer num = appointmentPayCancelMapper.getJzlsNum((long) ghxh);
        if(num > 0){
            baseResponse.setCode(Constant.errorTag);
            baseResponse.setMessage("该号已就诊，不能取消！");
            return baseResponse;
        }

        Long jgidLong = Long.valueOf(jgid);
//        String czgh = systemConfigMapper.getValueByConfigName(jgidLong, "ZSYY_MRGH");
        String czgh = "900001";
        //更新退号标志：
        //update MS_GHMX set THBZ = 1 where SBXH = :ll_sbxh and JGID = :go_jgxx.il_jgid using SQLHIS;
        appointmentPayCancelMapper.updateYyqxGhmx(ghxh, jgid);

        //插入MS_THMX
//	INSERT INTO MS_THMX(JGID,SBXH,CZGH,MZLB,THRQ)
        appointmentPayCancelMapper.updateYyqxThmx(ghxh, czgh, mzlb, now, jgid);

        //更新MS_YYGH
//	UPDATE MS_YYGH Set GHBZ = 4 Where JGID = :go_jgxx.il_jgid and SBXH = :ll_sbxh
        appointmentPayCancelMapper.updateYyqxYygh(ghxh, jgid);


//			判断ysdm是否为空
//			不为空则查找MS_YSPB
//			select count(1) into :ll_Count from MS_YSPB  //先判断专家是否有医生排班
//				WHERE JGID = :go_jgxx.il_jgid and YSDM = :ls_ysdm AND KSDM = :ls_ksdm AND MS_YSPB.GZRQ >= :ldt_begin AND
//						MS_YSPB.GZRQ <= :ldt_end AND MS_YSPB.ZBLB = :li_zblb
        if (ysdm != null && !"".equals(ysdm)) {
            Date kssj = null;
            Date jssj = null;
            kssj = DateUtil.getDateByZeroTime(yysj, 0);
            jssj = DateUtil.getDateByZeroTime(yysj, 1);
            int countYspb = appointmentPayCancelMapper.getCountYspb(ysdm, ksdm, kssj, jssj, zblb, jgid);
            if (countYspb > 0) {
                appointmentPayCancelMapper.updateYyqxYspb(ysdm, ksdm, kssj, jssj, zblb, jgid);

            }


        }

//			若有记录则更新预约人数和已挂人数
//			UPDATE MS_YSPB SET YYRS = YYRS - 1
//							WHERE JGID = :go_jgxx.il_jgid and YSDM = :ls_ysdm AND KSDM = :ls_ksdm AND MS_YSPB.GZRQ >= :ldt_begin AND
//							MS_YSPB.GZRQ <= :ldt_end AND MS_YSPB.ZBLB = :li_zblb

        //根据yysj计算ghrq
//        Date nowStart = DateUtil.getDateByZeroTime(now, 0);

//        if (yysj.getTime() >= nowStart.getTime()) {
            int ghrq = DateUtil.getDayofweek(yysj);
            int countKspb = appointmentPayCancelMapper.getCountKspb(ghrq, zblb, ksdm, jgid);
            if (countKspb > 0) {
                appointmentPayCancelMapper.updateYyqxkspb(ghrq, zblb, ksdm, jgid);
            }

//        }

//
//			退号成功

        baseResponse.setCode(Constant.successTag);
        return baseResponse;
    }

}
